# -*- encoding: utf-8 -*-
'''
Created on 2011-04-16

@author: quermit
'''
import os
import logging

from PyQt4 import uic
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QSize
from PyQt4.QtGui import QMainWindow
from PyQt4.QtGui import QAction
from PyQt4.QtGui import QIcon
from PyQt4.QtGui import QTreeWidgetItem
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QTableWidget

from core.stomp import Reader
from dialogs.logic.quotes import QuotesTable
from core.config import Config
from core.ldapint import LDAPIndexReader
from core.history import HistoryReader


log = logging.getLogger(__name__)


class MainDialog(QMainWindow):

    def __init__(self):
        super(MainDialog, self).__init__()
        self.ui = uic.loadUi("layouts/main.ui", self)

        self.__readers = {}
        self.__tabs = {}
        self.__index_data = {}

        self.__init_gui()
        self.__init_logic()
        self.__setup()

    def __init_gui(self):
        self.a_connect = QAction(QIcon("layouts/icons/connect.png"), "Connect", self)

        self.resize(QSize(960, 600))
        self.ui.toolbarMain.setIconSize(QSize(24, 24))
        self.ui.toolbarMain.addAction(self.a_connect)
        self.ui.tabQuotes.setMovable(True)

    def __init_logic(self):
        cfg = Config.instance()

        #self.__quotes_table = QuotesTable(self.ui.tableQuotes, refresh=1000)

        #self.__index_fetcher = IndexListFetcher(self, cfg.get("server", "register"))
        #self.__index_fetcher.finished.connect(self.__on_index_list_fetched)
        #self.__index_fetcher.start()

        addr = cfg.get('server', 'ldap-addr')
        path = cfg.get('server', 'ldap-data')
        self.__index_reader = LDAPIndexReader(self, addr, path)
        self.__index_reader.finished.connect(self.__on_index_fetched)
        self.__index_reader.start()

        self.ui.treeIndexes.itemClicked.connect(self.__on_index_clicked)

    def __on_index_clicked(self, item, column):
        is_checked = bool(item.checkState(0) == Qt.Checked)
        idx_name = unicode(item.text(0))

        if is_checked and idx_name not in self.__readers:
            log.info("Subscribing %s" % idx_name)
            data = self.__index_data[idx_name]

            quotes = QTableWidget(self)
            quotes.setColumnCount(5)
            quotes.setHorizontalHeaderLabels(["index", "quote", "turnover", "price", "change (session)"])
            quotes.setColumnWidth(0, 0)
            quotes.setColumnWidth(4, 120)
            quotes_tab = QuotesTable(quotes, refresh=1000)

            idx = self.tabQuotes.addTab(quotes_tab.get_widget(), idx_name)
            self.tabQuotes.setCurrentIndex(idx)

            history = HistoryReader(self, data['host'],
                                    int(data['port_history']), data['name'])
            history.onMessage.connect(quotes_tab.update_quote)
            history.start()

            reader = Reader(self, data['host'], int(data['port_queue']),
                            "jms.topic.%s" % data['topic'], data['name'])
            reader.onMessage.connect(quotes_tab.update_quote)
            reader.start()

            self.__readers[idx_name] = (reader, history)
            self.__tabs[idx_name] = quotes_tab

        if not is_checked and idx_name in self.__readers:
            log.info("Unsubscribing %s" % idx_name)
            reader, _ = self.__readers.pop(idx_name)
            reader.quit()

            tab = self.__tabs.pop(idx_name)
            idx = self.tabQuotes.indexOf(tab.get_widget())
            self.tabQuotes.removeTab(idx)

    def __on_index_fetched(self):
        if self.__index_reader.error:
            QMessageBox.critical(self, "Server error", str(self.__index_reader.error))
            return

        for region in self.__index_reader.result:
            log.info("Region: %s" % region['country'])

            top_item = QTreeWidgetItem([region['description']])
            self.ui.treeIndexes.addTopLevelItem(top_item)
            for index in region['indexes']:
                log.info("Index: %s" % index['name'])

                self.__index_data[index['name']] = index

                item = QTreeWidgetItem([index['name']])
                item.setToolTip(0, index['description'])
                item.setCheckState(0, Qt.Unchecked)
                top_item.addChild(item)

            top_item.setExpanded(True)


#    def __on_index_list_fetched(self):
#        error = self.__index_fetcher.get_error()
#        if error:
#            QMessageBox.critical(self, "Server error", error)
#            return
#        
#        wig_idx = QTreeWidgetItem(["WIG"])
#        self.ui.treeIndexes.addTopLevelItem(wig_idx)
#        
#        for data in self.__index_fetcher.get_result():
#            self.__index_data[data.name] = data
#            
#            item = QTreeWidgetItem([data.name])
#            item.setCheckState(0, Qt.Unchecked)
#            wig_idx.addChild(item)
#            
#        wig_idx.setExpanded(True)

    def __setup(self):
        login = self.user_sys_login()
        self.ui.statusBar.showMessage("Hello %s!" % login, 10000)

    def user_sys_login(self):
        return os.environ.get("USERNAME", os.environ.get("LOGIN", "unknown"))
